from flask import Blueprint, request, render_template, jsonify
from flask_login import login_required, current_user
from app.models import Request, Case, Patient, Doctor,Bed
from app.utils import custom_jsonify
from app import db

requesting_bp = Blueprint('requesting', __name__)

@requesting_bp.route('/requesting/my_request', methods=['GET'])
@login_required
def my_request():
    return render_template('my_request.html')

@requesting_bp.route('/requesting/deal_request', methods=['GET'])
@login_required
def deal_request():
    return render_template('deal_request.html')

@requesting_bp.route('/api/requests/my', methods=['GET'])
@login_required
def get_my_requests():
    try:
        # 获取当前用户的所有请求
        requests = Request.query.join(Case).filter(
            Case.doctor_id == current_user.doctor_id
        ).all()

        request_list = []
        for req in requests:
            case = Case.query.get(req.case_id)
            if case:
                patient = Patient.query.get(case.patient_id)
                doctor = Doctor.query.get(case.doctor_id)
                
                request_list.append({
                    'request_id': req.request_id,
                    'case_id': case.case_id,
                    'patient_name': patient.patient_name if patient else 'Unknown',
                    'bed_id': req.wanted_bed,
                    'dept_name': case.dept_name,
                    'doctor_name': doctor.doctor_name if doctor else 'Unknown',
                    'location': 'To be implemented',  # 需要根据床位ID获取位置
                    'request_status': req.request_status
                })
        
        return custom_jsonify({
            'msg': 'success',
            'requests': request_list
        })
    except Exception as e:
        return custom_jsonify({
            'msg': 'failed',
            'error': str(e)
        }, 500)

# @requesting



@requesting_bp.route('/api/case/<case_id>', methods=['GET'])
@login_required
def get_case_info(case_id):
    try:
        case = Case.query.get(case_id)
        if not case:
            return custom_jsonify({
                'msg': 'failed',
                'error': '病例不存在'
            }, 404)
            
        patient = Patient.query.get(case.patient_id)
        doctor = Doctor.query.get(case.doctor_id)
        
        return custom_jsonify({
            'msg': 'success',
            'case_info': {
                'case_id': case.case_id,
                'patient_name': patient.patient_name if patient else 'Unknown',
                'patient_id': case.patient_id,
                'doctor_name': doctor.doctor_name if doctor else 'Unknown',
                'dept_name': case.dept_name,
                'description': case.description,
                'predict_days': float(case.predict_days) if case.predict_days else 0
            }
        })
    except Exception as e:
        return custom_jsonify({
            'msg': 'failed',
            'error': str(e)
        }, 500)

@requesting_bp.route('/api/request/<request_id>/cancel', methods=['POST'])
@login_required
def cancel_request(request_id):
    try:
        req = Request.query.get(request_id)
        if not req:
            return custom_jsonify({
                'msg': 'failed',
                'error': '请求不存在'
            }, 404)
            
        req.request_status = 3  # 设置为已取消状态
        db.session.commit()
        
        return custom_jsonify({
            'msg': 'success'
        })
    except Exception as e:
        db.session.rollback()
        return custom_jsonify({
            'msg': 'failed',
            'error': str(e)
        }, 500)
    
##返回所有向我借床位的case

@requesting_bp.route('/api/requests/to_me')
@login_required
def get_requests_to_me():
    try:
        #获取当前用户id
        doctor_id = current_user.doctor_id
        print(doctor_id)
        my_bed = Bed.query.with_entities(Bed.bed_id).filter(Bed.doctor_id == doctor_id).all()

        my_bed = {value for (value,) in my_bed}
        requests = Request.query.filter(Request.wanted_bed.in_(my_bed)).all()
        request_list = []
        # print(type(requests))
        for req in requests:
            # print(req.to_string())
            case = Case.query.get(req.case_id)
            if case:
                patient = Patient.query.get(case.patient_id)
                doctor = Doctor.query.get(case.doctor_id)
                
                request_list.append({
                    'request_id': req.request_id,
                    'case_id': case.case_id,
                    'patient_name': patient.patient_name if patient else 'Unknown',
                    'bed_id': req.wanted_bed,
                    'dept_name': case.dept_name,
                    'doctor_name': doctor.doctor_name if doctor else 'Unknown',
                    'location': 'To be implemented',  # 需要根据床位ID获取位置
                    'request_status': req.request_status
                })
        print(request_list)
        return custom_jsonify({
            'msg': 'success',
            'requests': request_list
        })
    
        
    except Exception as e:
        db.session.rollback()
        return custom_jsonify({
            'msg': 'failed',
            'error': str(e)
        }, 500)
